const express = require('express');
const cors = require('cors');
const path = require('path');
require('dotenv').config();

// 导入路由
const adminRoutes = require('./routes/adminRoutes');
const clientRoutes = require('./routes/clientRoutes');
const userRoutes = require('./routes/userRoutes');
const parkingOperatorRoutes = require('./routes/parkingOperatorRoutes');
const authRoutes = require('./routes/authRoutes');
const changeRequestRoutes = require('./routes/changeRequestRoutes');

const app = express();

app.use(cors({
  origin: true, // 允许所有来源
  credentials: true
}));

app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true, limit: '10mb' }));

// 静态文件服务 - 用于访问上传的图片
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));

// API路由
app.use('/api/admin', adminRoutes);
app.use('/api/content', clientRoutes);
app.use('/api/parking', clientRoutes);
app.use('/api/coupon-center', clientRoutes);
app.use('/api/user', userRoutes);
app.use('/api/parking-operator', parkingOperatorRoutes);
app.use('/api/auth', authRoutes);
app.use('/api/change-requests', changeRequestRoutes);

// 基础路由
app.get('/', (req, res) => {
  res.json({
    message: '省米停车管理系统API服务',
    version: '1.0.0',
    status: 'running'
  });
});

// 健康检查路由
app.get('/health', (req, res) => {
  res.json({
    status: 'ok',
    timestamp: new Date().toISOString()
  });
});

// 404处理
app.use('*', (req, res) => {
  res.status(404).json({
    error: '接口不存在',
    path: req.originalUrl
  });
});

// 全局错误处理
app.use((error, req, res, next) => {
  console.error('服务器错误:', error);
  res.status(500).json({
    error: '服务器内部错误',
    message: process.env.NODE_ENV === 'development' ? error.message : '请联系管理员'
  });
});

module.exports = app;
